import Vue from 'vue'
import VueRouter from 'vue-router'

// 二级路由 默认加载
import Cart from '@/views/layout/cart'
import Home from '@/views/layout/home'
import Category from '@/views/layout/category'
import User from '@/views/layout/user'

import store from '@/store'
// 一级路由
// login下面是index，则不需要写index，直接写到login目录即可
// import Login from '@/views/login'
// import Layout from '@/views/layout'
// import Search from '@/views/search'
// import Order from '@/views/order'
// import Pay from '@/views/pay'
// import Prodetail from '@/views/prodetail'
// import SearchList from '@/views/search/list.vue'

// 一级路由懒加载，按需加载
const Login = () => import('@/views/login')
const Layout = () => import('@/views/layout')
const Search = () => import('@/views/search')
const Order = () => import('@/views/order')
const Pay = () => import('@/views/pay')
const Prodetail = () => import('@/views/prodetail')
const SearchList = () => import('@/views/search/list.vue')

Vue.use(VueRouter)

// 全局解决：解决二级路由跳转一级路由login时抛异常（Uncaught (in promise) Error）
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      redirect: '/home',
      children: [
        { path: '/home', component: Home },
        { path: '/category', component: Category },
        { path: '/cart', component: Cart },
        { path: '/user', component: User }

      ]
    },
    { path: '/search', component: Search },
    { path: '/searchlist', component: SearchList },
    { path: '/order', component: Order },
    { path: '/pay', component: Pay },
    { path: '/prodetail/:id', component: Prodetail }
  ]
})

// 全局前置守卫:所有路由在被访问到之前(渲染前)，都会经过前置守卫
// to 目标连接，from：来源链接
// next()直接放行
// 如果跳转next（跳转链接）
router.beforeEach((to, from, next) => {
  // console.log('全局前置守卫', to.path)
  if (authUrls.includes(to.path)) {
    // console.log('需要授权')
    const token = store.getters.getToken
    if (token.trim().length < 1) {
      // console.log('需要登录')
      // 需要授权的访问
      next('/login')
      return
    }
  }

  // 非权限页面直接放行
  // console.log('正在放行')
  next()
})
// 定义权限访问页面
const authUrls = ['/pay', '/order']
export default router
